package com.tang.common.listener;

import com.tang.common.constant.UniversalConstant;
import com.tang.common.event.ApiLogEvent;
import com.tang.module.system.entity.LogApi;
import com.tang.module.system.mapper.LogApiMapper;
import com.tang.module.useapi.module.entity.IpLocation;
import com.tang.module.useapi.module.resources.BasicUseApiResources;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author tang
 * @date 2022/1/19 10:57
 */
@Slf4j
@Component
public class ApiLogListener implements ApplicationListener<ApiLogEvent> {

    @Resource
    private LogApiMapper logApiMapper;

    @Resource
    private BasicUseApiResources basicUseApiResources;


    @Async
    @Override
    public void onApplicationEvent(ApiLogEvent event) {
        LogApi logApi = event.getLogApi();
        //获取用户所在地址和运营商,本地IP不需要请求接口
        if (UniversalConstant.LOCALHOST_IP.equals(event.getLogApi().getRemoteIp())) {
            logApi.setAddress("本地");
            logApi.setIsp("本地");
        }else {
            IpLocation ipLocation = basicUseApiResources.byIpGetLocation(event.getLogApi().getRemoteIp());
            logApi.setAddress(
                            //国家
                            (ipLocation.getCountry() == null? "" : ipLocation.getCountry()) +
                            //省份
                            (ipLocation.getProvince() == null? "" : "-" + ipLocation.getProvince()) +
                            //市
                            (ipLocation.getCity() == null? "" : "-" + ipLocation.getCity()) +
                            //区
                            (ipLocation.getDistrict() == null? "" : "-" + ipLocation.getDistrict()));
            logApi.setIsp(ipLocation.getIsp());
        }
        logApiMapper.insert(logApi);
    }
}
